<template>
    <view class="page-verification-code" :style="`padding-top: ${statusBarHeight}px`">
        <PageHeader>
            <template #left>
                <view class="back" @tap="navBack"> <uni-icons type="left" color="#1e232c" size="18px" /> </view>
            </template>
            <template #right>
                <!-- <view class="skip"> 跳过 </view> -->
            </template>
        </PageHeader>
        <view class="content">
            <view class="welcome-title">请输入验证码</view>
            <view class="subtitle">验证码已发送至您的手机尾号{{ phoneTail }}</view>

        <!-- 验证码输入框 -->
        <view class="code-container">
            <input v-for="(item, index) in codeArray" :key="index" :ref="el => setInputRef(el, index)"
                class="code-input" type="number" inputmode="numeric" maxlength="1" v-model="codeArray[index]"
                @input="handleInput(index, $event)" @focus="handleFocus(index)" @keydown="handleKeyDown(index, $event)"
                :focus="currentFocusIndex === index" />
        </view>

        <!-- 重新获取验证码 -->
        <view class="resend-container">
            <text v-if="countdown > 0" class="resend-text">{{ countdown }}秒后重新获取</text>
            <text v-else class="resend-text active" @click="handleResend">重新获取验证码</text>
        </view>
        </view>
        <!-- 验证按钮 -->
        <view class="primary-button" :class="{ disabled: !isCodeComplete }"
            @click="handleVerify">
            验证
        </view>
    </view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed, onMounted, nextTick } from 'vue';
import PageHeader from '@/components/page-header'
import { getCodeVerify, verifyCodeLogin } from '@/api/user'
import store from '@/store/index.js';
import { toast } from '@/utils/common'
const statusBarHeight = computed(() => store.state.systemInfo.statusBarHeight)

const phone = ref('')
// 模拟手机尾号
const phoneTail = ref('');

// 验证码数组（6位）
const codeArray = ref(['', '', '', '']);
const currentFocusIndex = ref(0);
const countdown = ref(60);
const inputRefs = ref([]);

// 计算属性：验证码是否输入完整
const isCodeComplete = computed(() => {
    return codeArray.value.every(item => item !== '');
});

// 处理输入
const handleInput = (index, e) => {
    const value = e.detail.value;

    // 过滤非数字字符
    if (!/^\d*$/.test(value)) {
        codeArray.value[index] = '';
        return;
    }

    // 自动聚焦到下一个输入框
    if (value && index < codeArray.value.length - 1) {
        currentFocusIndex.value = index + 1;
        nextTick(() => {
            inputRefs.value[index + 1].focus();
        });
    }
};

// 处理键盘事件
const handleKeyDown = (index, e) => {
    const keyCode = e.keyCode || e.detail?.keyCode || 0;

    if (keyCode === 8) { // Backspace键
        // 如果当前框为空，且不是第一个框，则删除前一个框的内容并聚焦
        if (!codeArray.value[index] && index > 0) {
            codeArray.value[index - 1] = '';
            currentFocusIndex.value = index - 1;

            // 确保DOM更新后执行聚焦
            nextTick(() => {
                inputRefs.value[index - 1].focus();
            });
        }
    }
};

// 处理聚焦
const handleFocus = (index) => {
    currentFocusIndex.value = index;

    // 聚焦时选中文本方便重新输入
    nextTick(() => {
        const input = inputRefs.value[index];
        if (input) {
            input.setSelectionRange(0, 1);
        }
    });
};

// 处理验证
const handleVerify = async () => {
    if (!isCodeComplete.value) {
        toast({ icon: 'none', title: '请输入验证码' })
        return
    };

    try {
        const randomCode = codeArray.value.join('');
        const { code, msg } = await verifyCodeLogin({ phone: phone.value, randomCode })
        if (code === 0) {
            toast({ icon: 'success', title: '验证成功' }, () => {
                // 验证成功后跳转
                uni.redirectTo({
                    url: '/pages/home/index'
                });
            });
            return
        }
        toast({ title: msg, icon: 'none' })
    } catch (e) {
        toast({
            title: `验证失败，请稍后再试`,
            icon: 'none'
        });
    }
};

// 处理重新获取
const handleResend = async () => {
    if (countdown.value > 0) return;


    try {
        const { data } = await getCodeVerify({ phone: phone.value })

        const { code } = data

        if (code === 0) {
            toast({
                title: '验证码已重新发送',
                icon: 'none'
            });

            // 重置倒计时
            countdown.value = 60;
            startCountdown();

            // 清空验证码
            codeArray.value = ['', '', '', ''];
            currentFocusIndex.value = 0;
        } else {
            toast({
                title: '验证码发送失败，请稍后再试',
                icon: 'none'
            });
        }
    } catch (e) {

    }
    
};

// 倒计时
const startCountdown = () => {
    const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
            clearInterval(timer);
        }
    }, 1000);
};

// 初始化输入框引用
const setInputRef = (el, index) => {
    if (el) {
        inputRefs.value[index] = el;
    }
};

// 返回
const navBack = () => {
    uni.navigateBack();
};


onLoad((opt) => {
    console.log(opt, 'opt----')
    // 获取传过来的手机号
    phone.value = opt.phone || ''
    console.log(phone.value, 'phone.value')
    // 尾号展示
    phoneTail.value = phone.value ? phone.value.slice(-4) : ''
})

onMounted(() => {
    startCountdown();
});
</script>

<style lang="scss">
.page-verification-code {

    .content {
        padding: 0 50px;
        box-sizing: border-box;
    }
    
}

.back {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 60rpx;
    height: 60rpx;
    border-radius: 10rpx;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(232, 236, 244, 1);
}

.skip {
    width: 48px;
    height: 29px;
    font-size: 24px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 28.13px;
    color: rgba(0, 152, 255, 1);
    text-align: center;
    vertical-align: top;
}

.welcome-title {
    margin: 68px auto 20px;
    font-size: 32px;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 18.75px;
    color: rgba(0, 0, 0, 1);
    vertical-align: bottom;
}

.subtitle {
    width: 80vw;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 80rpx;
}

.code-container {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-bottom: 60rpx;
}

.code-input {
    width: 100rpx;
    height: 100rpx;
    text-align: center;
    font-size: 48rpx;
    border: 2rpx solid #e8ecf4;
    border-radius: 12rpx;

    &:focus {
        border-color: #35c2c1;
    }
}

.resend-container {
    margin-bottom: 80rpx;
    width: 100%;
    text-align: center;
}

.resend-text {
    font-size: 28rpx;
    color: #999;

    &.active {
        color: #007AFF;
    }
}

.primary-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100vw - 50px);
        height: 48px;
        margin: 0 auto;
        opacity: 1;
        border-radius: 8.02px;
        background: #5d5fef;
        box-shadow: 0px 0px 0px 6.42px #ffffff26;
       
        font-size: 18px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 21.1px;
        color: rgba(255, 255, 255, 1);
        text-align: center;

        &.disabled {
            opacity: 1;
            background-color: #eee;
        }
    }
</style>